package edu.yourl.persistence;

import java.util.List;

import com.db4o.query.Predicate;

import edu.yourl.domain.User;
import edu.yourl.domain.exception.NicknameAlreadyRegisteredException;

public class UserRepository extends AbstractRepository implements IUserRepository {

	private static final String NICKNAME_FIELD = "nickname";

	@Override
	public void addUser(User user) throws NicknameAlreadyRegisteredException {
		User existing = getUser(user.getNickname());
		if (existing == null) {
			this.add(user);
		} else {
			throw new NicknameAlreadyRegisteredException();
		}
	}

	public List<User> searchUsers(final String stringToSearch) {
		Predicate<User> fuzzyPredicate = new Predicate<User>() {

			private static final long serialVersionUID = 1L;

			@Override
			public boolean match(User arg0) {
				boolean inName = false;
				boolean inNick = false;
				if (arg0.getName() != null) {
					inName = arg0.getName().contains(stringToSearch);
				}
				if (arg0.getNickname() != null) {
					inName = arg0.getNickname().contains(stringToSearch);
				}
				return inName || inNick;
			}
		};
		return this.get(fuzzyPredicate);
	}

	@Override
	public User getUser(String nick) {
		if (nick != null) {
			List<User> usersWithSameNick = this.getByPropertyValue(User.class, NICKNAME_FIELD, nick);
			if (!usersWithSameNick.isEmpty()) {
				return usersWithSameNick.get(0);
			} else {
				return null;
			}
		}
		
		return null;
	}
	
}
